package com.boot.configstatistical.repair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dmall.order.domain.Order;
import com.dmall.order.domain.PaymentDetailVO;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

/**
 * @author Administrator
 * @className ApportGroupIdRepairScript
 * @description
 * @date 2024/2/26 9:58
 **/
public class ApportGroupIdRepairScript {


  public static Order deal(String orderId, String Cookie) throws Exception {

          String url = "http://man.order.dmall.com/showOrderJSONData?orderId=" + orderId;

          // 创建CookieStore对象
          BasicCookieStore cookieStore = new BasicCookieStore();

          // 创建HttpClient对象
          CloseableHttpClient httpClient = HttpClients.custom()
              .setDefaultCookieStore(cookieStore)
              .build();

          // 创建HttpGet对象并设置请求头Cookie信息
          HttpGet httpGet = new HttpGet(url);
          httpGet.addHeader("Cookie", Cookie);

          // 执行请求并获取响应
          HttpClientContext context = HttpClientContext.create();
          CloseableHttpResponse result = httpClient.execute(httpGet, context);

          Order order = new Order();
          // 输出响应内容
          if (result.getStatusLine().getStatusCode() == 200) {
            String html = EntityUtils.toString(result.getEntity(), "UTF-8");
            JSONObject jsonObject =  JSON.parseObject(html);
            String orderStr =String.valueOf(jsonObject.get("data"));
            order = JSONObject.parseObject(orderStr, Order.class);
            System.out.println(JSONObject.toJSONString(order));
          }
          // 关闭资源
          result.close();
          httpClient.close();
          return order;
  }

    public static void dealData(String orderId) throws Exception {
      String cookie = "GALAXY_OFFLINE_CLIENT_WEB_VERSION_9e74bd830361046daa00798aa282f1fe=10; dhrUserId=9157561; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2218ba7d63fe0633-02cc4ef12e489f-26031051-2304000-18ba7d63fe1cdc%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMThiYTdkNjNmZTA2MzMtMDJjYzRlZjEyZTQ4OWYtMjYwMzEwNTEtMjMwNDAwMC0xOGJhN2Q2M2ZlMWNkYyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218ba7d63fe0633-02cc4ef12e489f-26031051-2304000-18ba7d63fe1cdc%22%7D; loginType=account; appname=cloud; username=songlin.an; timeZone=Asia/Shanghai; language=zh; zone=gz01; envRootDomain=dmall.com; signature=005cdf78ccffca3789ab2bc4d4718060; timestamp=1708763429; UYBFEWAEE=9DEFB1D8615C14E04C91DC78BE64478CCB124D844442FF36C428BA2B3B1EA906CBEA68E65C2EFD499D75C74B81FDBEBB2463D7073479427896731547200FA203; login_no=eW9uZy56aGFvXzE1ODI4NTM4Mzg3; cur_partner_pc_menu=%5B%7B%22k%22%3A-1%2C%22n%22%3A%22os%u7F51%u9875%u7248%22%2C%22p%22%3A-1%2C%22l%22%3A-1%2C%22r%22%3A-1%7D%5D; return_url=https://aladdin.dmall.com/#index/aladdin_h5/devops/projectManage/fastdeploy:projectId=7047432727315874112&foreignId=dmall-pay-cabinx-asm&env=test; login_token=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDgzMDc0MzQ1NDksImV4cCI6MTcwODkxMjIzNDU0OSwiaXNzIjoia2VuIiwiZGF0YSI6eyJ1c2VyX2luZm8iOnsidXNlcl9pZCI6OTE1NzU2MSwidXNlcl9jb2RlIjoic29uZ2xpbi5hbiIsInVzZXJfbmFtZSI6Ilx1NWI4OVx1Njc3ZVx1Njc5NyIsInByZWZlcnJlZF9uYW1lIjoiXHU1Yjg5XHU2NzdlXHU2Nzk3IiwicGhvbmUiOiIiLCJlbWFpbCI6InNvbmdsaW4uYW5AZG1hbGwuY29tIiwiaHJzX2lkIjo4NjQzOTYxLCJocm1zX2lkIjoxMDAwMTMwODQxLCJ1c2VyX25vIjoiMTAwMDAxMjU4In0sImxvZ2luX3RpbWUiOjE3MDgzMDc0MzQ1NDl9fQ.qBgAEsv-F3YCaJDO1F_Oywb_pSylBn_KRxA-bA6jpIk; login_user_name=%E5%AE%89%E6%9D%BE%E6%9E%97; login_type=vpn; login_dmall_id=songlin.an; wm_menu_id=menu_4333";
      Order order = ApportGroupIdRepairScript.deal(orderId, cookie);
      List<PaymentDetailVO> paymentDetails = order.getPaymentDetails();
      //遍历paymentDetails，判断里面的groupId是不是全部一样，如果一样就取出来然后转换成数字再随机加一个10以内的数字，然后再回填回去
      List<String> collect = paymentDetails.stream().map(PaymentDetailVO::getGroupId)
          .collect(Collectors.toList());
      for (PaymentDetailVO paymentDetail : paymentDetails) {
        String groupId = paymentDetail.getGroupId();
        if (StringUtils.isEmpty(groupId)) {
          continue;
        }
        if (collect.contains(groupId)) {
          int groupIdInt = Integer.parseInt(groupId);
          int random = (int) (Math.random() * 10);
          paymentDetail.setGroupId(String.valueOf(groupIdInt + random));
        }
      }
      order.setPaymentDetails(paymentDetails);
      reApport(order);
    }


  //重新分摊
      public static void reApport(Order order) throws Exception {
        // 创建HttpClient实例
        HttpPost client = new HttpPost();

        // 创建请求体的JSON字符串
        String jsonBody =JSONObject.toJSONString(order);

        // 创建请求
        String url = "http://10.28.16.25:8080/apportion/complete/payCompleteApportion";
        client.setURI(URI.create(url));
        client.setHeader("Content-Type", "application/json");
        client.setHeader("Accept", "application/json");
        client.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));

        // 执行请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(client);
        String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject jsonObject = JSONObject.parseObject(responseString);
        Object o = jsonObject.get("msg");
        boolean success = o.equals("SUCCESS");
        if (success) {
          System.out.println("SUCCESS");
        } else {
        throw new Exception("重新分摊失败");
        }
        System.out.println(responseString);
      }


      public static void main(String[] args) throws Exception {
        String orderId[]  = {
            "752706830553",
            "752712823249",
            "752735086748"
        };

        for (String ordernO : orderId) {
          dealData(ordernO);
        }


      }
}
